package com.zbkj.admin.boot.servlet.context;

import com.zbkj.admin.boot.context.MicaContextProperties;
import com.zbkj.admin.boot.context.MicaHttpHeadersGetter;
import lombok.RequiredArgsConstructor;
import net.dreamlu.mica.core.context.IMicaContext;
import net.dreamlu.mica.core.utils.StringUtil;
import net.dreamlu.mica.core.utils.ThreadLocalUtil;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.lang.Nullable;

import java.util.function.Function;

/**
 * mica servlet 上下文，跨线程失效
 *
 * @author L.cm
 */
@RequiredArgsConstructor
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
public class MicaServletContext implements IMicaContext {
	public static final String CONTEXT_KEY = MicaServletContext.class.getName();
	private final MicaContextProperties contextProperties;
	private final MicaHttpHeadersGetter httpHeadersGetter;

	@Nullable
	@Override
	public String getRequestId() {
		return get(contextProperties.getHeaders().getNameRequestId());
	}

	@Nullable
	@Override
	public String getTenantId() {
		return get(contextProperties.getHeaders().getNameTenantId());
	}

	@Nullable
	@Override
	public String getAccountId() {
		return get(contextProperties.getHeaders().getNameAccountId());
	}

	@Nullable
	@Override
	public String get(String ctxKey) {
		HttpHeaders headers = ThreadLocalUtil.getIfAbsent(CONTEXT_KEY, httpHeadersGetter::get);
		if (headers == null || headers.isEmpty()) {
			return null;
		}
		return headers.getFirst(ctxKey);
	}

	@Nullable
	@Override
	public <T> T get(String ctxKey, Function<String, T> function) {
		String ctxValue = get(ctxKey);
		if (StringUtil.isBlank(ctxValue)) {
			return null;
		}
		return function.apply(ctxKey);
	}

}
